import { createSlice, createAsyncThunk } from '@reduxjs/toolkit'
import {
  getTopBanner,
  getHotRecommend,
  getNewAlbum,
  getPlayListDetail,
  getArtistList
} from '../service/recommend'
import { Banner, HotTag } from '@/types/common-types'

interface IRecommendState {
  banners: Banner[]
  hotRecommends: HotTag[]
  newAlbums: any[]
  albumList: []
  rankings: any[]
  settleSingers: any[]
}

export const fetchBannerDataAction = createAsyncThunk(
  'banners',
  async (_, { dispatch }) => {
    const res: any = await getTopBanner()
    dispatch(changeBannerAction(res.banners))
  }
)

export const fetcHotRecommendAction = createAsyncThunk(
  'hotRecommends',
  async (_, { dispatch }) => {
    const res: any = await getHotRecommend()
    dispatch(changeHotRecommendAction(res.result))
  }
)

export const fetchNewAlbumAction = createAsyncThunk(
  'newAlbums',
  async (_, { dispatch }) => {
    const res: any = await getNewAlbum()
    dispatch(changeNewAlbumAction(res.albums))
  }
)

const rakingIds = [19723756, 3779629, 2884035]

export const fetchTopListAction = createAsyncThunk(
  'rakingData',
  async (_, { dispatch }) => {
    const promises: Promise<any>[] = []
    for (const id of rakingIds) {
      promises.push(getPlayListDetail(id))
    }
    Promise.all(promises).then((res) => {
      const playLists = res.map((item) => {
        return {
          playlist: item.playlist,
          tracks: item.playlist?.tracks.slice(0, 10) || []
        }
      })
      dispatch(changeTopListAction(playLists))
    })
  }
)

export const fetchSettleSingerAction = createAsyncThunk(
  'settleSingers',
  async (_, { dispatch }) => {
    const res: any = await getArtistList(5)
    dispatch(changeSettleSingerAction(res.artists))
  }
)

const initialState: IRecommendState = {
  banners: [],
  hotRecommends: [],
  newAlbums: [],
  albumList: [],
  rankings: [],
  settleSingers: []
}

const recommendSlice = createSlice({
  name: 'recommend',
  initialState,
  reducers: {
    changeBannerAction(state, { payload }) {
      state.banners = payload
    },
    changeHotRecommendAction(state, { payload }) {
      state.hotRecommends = payload.slice(0, 8)
    },
    changeNewAlbumAction(state, { payload }) {
      state.newAlbums = payload
    },
    changeAlbumListAction(state, { payload }) {
      state.albumList = payload
    },
    changeTopListAction(state, { payload }) {
      state.rankings = payload
    },
    changeSettleSingerAction(state, { payload }) {
      state.settleSingers = payload
    }
  }
})

export const {
  changeBannerAction,
  changeHotRecommendAction,
  changeNewAlbumAction,
  changeAlbumListAction,
  changeTopListAction,
  changeSettleSingerAction
} = recommendSlice.actions

export default recommendSlice.reducer
